#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

// 互斥锁变量
pthread_mutex_t mutex1;
pthread_mutex_t mutex2;

void * fun1(void * arg){
    // 加锁
    pthread_mutex_lock(&mutex1);
    printf("thread 1 get 1 sources\n");
    printf("thread 1 get 1 sources\n");
    printf("thread 1 get 1 sources\n");
    pthread_mutex_lock(&mutex2);
    printf("thread 1 get 2 sources\n");
    // 解锁
    pthread_mutex_unlock(&mutex1);
    pthread_mutex_unlock(&mutex2);
    return NULL;
}

void * fun2(void * arg){
    // 加锁
    pthread_mutex_lock(&mutex2);
    printf("thread 2 get 2 sources\n");
    printf("thread 2 get 2 sources\n");
    printf("thread 2 get 2 sources\n");
    pthread_mutex_lock(&mutex1);
    printf("thread 2 get 1 sources\n");
    // 解锁
    pthread_mutex_unlock(&mutex2);
    pthread_mutex_unlock(&mutex1);
    return NULL;
}

/**
 * 死锁的演示性代码
 * @return
 */
int main(){
    pthread_t tid1;
    pthread_t tid2;

    int ret = -1;

    // 初始化
    ret = pthread_mutex_init(&mutex1,NULL);
    ret = pthread_mutex_init(&mutex2,NULL);

    printf("初始化 互斥锁 成功！");

    memset(&tid1,0,sizeof(tid1));
    memset(&tid2,0,sizeof(tid2));
    ret = pthread_create(&tid1,NULL,fun1,NULL);
    ret = pthread_create(&tid2,NULL,fun2,NULL);
    printf("main run\n");
    // 阻塞等待线程运行结束，并且获取线程的返回指针
    ret = pthread_join(tid1,NULL);
    ret = pthread_join(tid2,NULL);
    printf("\n");
    printf("main exit\n");
    // 销毁
    pthread_mutex_destroy(&mutex1);
    pthread_mutex_destroy(&mutex2);
    printf("销毁 互斥锁 成功！\n");
    return 0;
}
